//
//  SHSearchViewController.m
//  SHWheel
//
//  Created by YYKJ on 2020/9/27.
//  Copyright © 2020 YYKJ. All rights reserved.
//

#import "SHSearchViewController.h"
#import "ResultTableViewController.h"

@interface SHSearchViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) ResultTableViewController *resultVC;
@property (nonatomic, strong) NSArray *array;
@property (nonatomic, strong) NSMutableArray *results;

@property (nonatomic, assign) BOOL isActive;

@end

@implementation SHSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
//    self.edgesForExtendedLayout = UIRectEdgeNone;

    [self configDataSource];
    [self configUI];
}

- (void)configUI {
    self.title = @"Search";
    self.view.backgroundColor = UIColor.whiteColor;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT - 64) style:UITableViewStylePlain];
    tableView.backgroundColor = UIColor.whiteColor;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.rowHeight = 50;
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"dushcellId"];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    // 创建用于展示搜索结果的控制器
    ResultTableViewController *result = [[ResultTableViewController alloc] init];
    self.resultVC = result;
    // 创建UISearchController, 这里使用当前控制器来展示结果
    UISearchController *search = [[UISearchController alloc] initWithSearchResultsController:result];
    search.view.backgroundColor = UIColor.clearColor;
    search.searchResultsUpdater = self;
    if (@available(iOS 13.0, *)) {
        search.automaticallyShowsScopeBar = NO;
    } else {
        // Fallback on earlier versions
    }
    search.hidesNavigationBarDuringPresentation = NO;
    // 因为在当前控制器展示结果, 所以不需要这个透明视图
    search.dimsBackgroundDuringPresentation = YES;
    search.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    search.searchBar.returnKeyType = UIReturnKeyDone;
    search.searchBar.backgroundColor = UIColor.whiteColor;
    search.searchBar.backgroundImage = [UIImage new];
    search.searchBar.delegate = self;
    self.searchController = search;
    self.resultVC = result;
    
    tableView.tableHeaderView = search.searchBar;
//    if (@available(iOS 11.0, *)) {
//        self.navigationItem.searchController = search;
//    } else {
//        // Fallback on earlier versions
//    }
    
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.definesPresentationContext = YES;
    self.navigationController.navigationBar.translucent = NO;
}

- (void)configDataSource {
    
    NSMutableArray *data = [NSMutableArray array];
    for (int i = 0; i<30; i++) {
        [data addObject: [NSString stringWithFormat:@"%d", i]];
    }
    self.array = data.copy;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.tableView.frame = self.view.bounds;
}

#pragma mark - Privite func
- (void)search:(NSString *)searchString {
    /**
     * 在当前页面进行搜索
    if (self.results.count > 0) {
        [self.results removeAllObjects];
    }
    for (NSString *str in self.array) {
        if ([str.lowercaseString rangeOfString:searchString.lowercaseString].location != NSNotFound) {
            [self.results addObject:str];
        }
    }
    [self.tableView reloadData];
     */
    
    // 在 resultVC 页面进行搜索
    if (self.results.count > 0) {
        [self.results removeAllObjects];
    }
    for (NSString *str in self.array) {
        if ([str.lowercaseString rangeOfString:searchString.lowercaseString].location != NSNotFound) {
            [self.results addObject:str];
        }
    }
    
    self.resultVC.filterResults = self.results;
}

#pragma mark - Over write

#pragma mark - Event Response

#pragma mark - Data handle

#pragma mark - Request

#pragma mark - Delegate & datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.isActive ? self.results.count : self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dushcellId"];
    NSString *string = self.isActive ? self.results[indexPath.row] : self.array[indexPath.row];
    cell.textLabel.text = string;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark -
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *inputStr = searchController.searchBar.text;
    if (inputStr.length == 0) {
        return;
    }
    [self search:inputStr];
}

#pragma mark - SearchBar delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
//    self.isActive = YES;
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    self.isActive = NO;
    self.searchController.searchBar.text = @"";
    [self.tableView reloadData];
}

#pragma mark - Getter
- (NSArray *)results {
    if (!_results) {
        _results = [NSMutableArray array];
    }
    return _results;
}

@end
